#include "Console.h"

#include <iostream>


static RConsole* Instance=nullptr;

void RConsole::Initialize()
{
    assert(Instance==nullptr);
    Instance=this;
}

void RConsole::Deinitialize()
{
    assert(Instance!=nullptr);
    Instance=nullptr;
}

RConsole::RConsole()
{
// #ifdef WIN32
//     PrintString(U"using chcp 65001 for utf8 codec");
//     std::system("chcp 65001"); //force console use utf8 codec
// #endif
}

RConsole *RConsole::Get()
{
    return Instance;
}

void RConsole::PrintLine(const CString &InMessage)
{
    PrintString(InMessage,true);
}

void RConsole::PrintString(const CString &InMessage, bool EndLine)
{
    //print to std out
    auto U8String = InMessage.ToUtf8();
    std::cout<<(const char *)U8String.Data();
    if(EndLine)
    {
        std::cout<<std::endl;
    }
    //flush
    std::cout.flush();

    //broadcast
    RConsole* Console=RConsole::Get();
    if(Console)
    {
        CString Message = InMessage;
        if(EndLine)
        {
            Message+=U"\n";
        }
        Console->OnPrint.Broadcast(Message);
    }
}

void RConsole::ErrorLine(const CString &InMessage)
{
    ErrorString(InMessage,true);
}

void RConsole::ErrorString(const CString &InMessage, bool EndLine)
{
    //输出到标注错误，错误不需要flush刷新
    auto U8String = InMessage.ToUtf8();
    std::cerr<<(const char *)U8String.Data();
    if(EndLine)
    {
        std::cerr<<std::endl;
    }
}
